package com.example.myapplication.module_common_service;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.BootstrapDropDown;
import com.beardedhen.androidbootstrap.api.attributes.BootstrapBrand;
import com.bumptech.glide.Glide;
import com.example.myapplication.R;
import com.example.myapplication.data.BookBorrow;
import com.example.myapplication.data.CourseScore;
import com.example.myapplication.data.GlobalData;
import com.example.myapplication.data.MySchedule;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class CourseScoreFragment extends Fragment {

    BootstrapDropDown bootstrapDropDown;
    // 用户选择的选项
    String year;
    String term;

    ListView dataList;
    List<CourseScore> data = new ArrayList<>();

    boolean selectYear = false;
    boolean selectTerm = false;

    private final int GET_DATA = 1;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case GET_DATA:
                    data.clear();
                    if(msg.obj!=null){
                        data.addAll((List<CourseScore>) msg.obj);
                    }
                    dataList.setAdapter(new CourseAdapter(data,getLayoutInflater(),getContext()));
                    break;
            }

        }
    };
    public CourseScoreFragment() {
        // Required empty public constructor
    }

    public static CourseScoreFragment newInstance(String param1, String param2) {
        CourseScoreFragment fragment = new CourseScoreFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_course_score, container, false);
        bootstrapDropDown = view.findViewById(R.id.dropdown);
        bootstrapDropDown.setDropdownData(new String[]{
                "2019-2020",
                "2020-2021",
                "2021-2022",
                "2022-2023",
        });
        bootstrapDropDown.setBackgroundColor(Color.argb(80,0,0,255));
        bootstrapDropDown.setTextColor(Color.BLACK);
        bootstrapDropDown.setOnDropDownItemClickListener(new BootstrapDropDown.OnDropDownItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, View v, int id) {
                TextView t = v.findViewById(id);
                bootstrapDropDown.setText(t.getText().toString());
                year = t.getText().toString();
                selectYear = true;
            }
        });
        view.findViewById(R.id.id_shangXueQi).setOnClickListener(view1 -> {
            term = "上学期";
            selectTerm = true;
            view.findViewById(R.id.id_xiaXueQi).setBackgroundColor(Color.argb(80,0,0,255));
            view.findViewById(R.id.id_shangXueQi).setBackgroundColor(Color.argb(80,255,0,0));
            getData();
        });
        view.findViewById(R.id.id_xiaXueQi).setOnClickListener(view1 -> {
            term = "下学期";
            selectTerm = true;
            view.findViewById(R.id.id_shangXueQi).setBackgroundColor(Color.argb(80,0,0,255));
            view.findViewById(R.id.id_xiaXueQi).setBackgroundColor(Color.argb(80,255,0,0));
            getData();
        });
        this.dataList = view.findViewById(R.id.list_scores);

        getData();
        this.dataList.setFooterDividersEnabled(false);
        this.dataList.setDividerHeight(2);
        this.dataList.setAdapter(new CourseAdapter(data,getLayoutInflater(),getContext()));


        return view;
    }


    // 获取学期成绩
    private void getData() {
        if(selectTerm&&selectYear){
            new Thread(new Runnable() {
                @Override
                public void run() {

                    OkHttpClient okHttpClient = new OkHttpClient();

                    String substring = GlobalData.jwt.substring(1, GlobalData.jwt.length() - 1);
                    Request request = new Request.Builder().
                            url("http://120.25.230.35:8080/scoreByTermAndYear?term="+term+"&year="+year).addHeader("jwt", substring).get().build();
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response execute = call.execute();
                        if(execute.isSuccessful()){
                            Message message = new Message();
                            //把jwt传进去
                            String string = execute.body().string();
                            Gson gson = new Gson();
                            List<CourseScore> dataX = gson.fromJson(string, new TypeToken<List<CourseScore>>() {
                            }.getType());
                            message.what = GET_DATA;
                            message.obj = dataX;

                            handler.sendMessage(message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }


    private class CourseAdapter extends BaseAdapter {
        private List<CourseScore> data;
        private LayoutInflater layoutInflater;
        private Context context;
        /**
         * 组件集合，对应list.xml中的控件
         *
         * @author Administrator
         */
        public final class ViewHolder {
            public TextView course_name;
            public TextView course_score;
            public TextView course_xuefen;
        }

        public CourseAdapter(List<CourseScore> data, LayoutInflater layoutInflater, Context context) {
            this.data = data;
            this.layoutInflater = layoutInflater;
            this.context = context;
        }

        @Override
        public int getCount() {
            return data.size() ;
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return data.get(i).getId();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            CourseAdapter.ViewHolder viewHolder = null;

            if (convertView == null) {
                viewHolder = new CourseAdapter.ViewHolder();
                //获得组件，实例化组件
                convertView = layoutInflater.inflate(R.layout.layout_for_score_display, null);
                viewHolder.course_name= convertView.findViewById(R.id.score_cname);
                viewHolder.course_score = convertView.findViewById(R.id.score_score_get);
                viewHolder.course_xuefen = convertView.findViewById(R.id.score_xueFen);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (CourseAdapter.ViewHolder) convertView.getTag();
            }
            //绑定数据
            viewHolder.course_name.setText(this.data.get(position).getName());
            viewHolder.course_score.setText(this.data.get(position).getScore().toString());
            viewHolder.course_xuefen.setText(this.data.get(position).getXueFen().toString());
            return convertView;
        }
    }

}